package com.cssy.yd.logic.web;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSONArray;
import com.cssy.authority.entity.ScDepartmentDO;
import com.cssy.authority.service.IScDepartmentService;
import com.cssy.base.web.BaseController;
import com.cssy.base.web.BodyMsg;
import com.cssy.yd.basic.entity.BasicCompanyDO;
import com.cssy.yd.basic.entity.BasicModeDeliveryDO;
import com.cssy.yd.basic.entity.BasicModePaymentDO;
import com.cssy.yd.basic.service.IBasicCompanyService;
import com.cssy.yd.basic.service.IBasicModeDeliveryService;
import com.cssy.yd.basic.service.IBasicModePaymentService;
import com.cssy.yd.logic.entity.LogicPoDO;
import com.cssy.yd.logic.entity.LogicPoItemDO;
import com.cssy.yd.logic.entity.LogicPoQuoteDO;
import com.cssy.yd.logic.entity.LogicPoQuoteItemDO;
import com.cssy.yd.logic.service.ILogicPoQuoteItemService;
import com.cssy.yd.logic.service.ILogicPoQuoteService;
import com.plat.exception.SyBaseException;
import com.plat.helper.JqGridHandler;
import com.plat.helper.SearchCondition;
import com.plat.helper.SearchConditions;
import com.plat.helper.SearchResult;
import com.plat.util.GlobalResLoader;
import com.plat.util.OperationFlag;
import com.plat.util.SessionUtil;
import com.plat.util.json.AjaxUtil;
import com.plat.util.json.OutJsonGrid;
import com.yuendong.sy.service.code.SyCodeType;
import com.yuendong.sy.service.code.impl.SyCodeService;

@Controller
@RequestMapping("/yd/logic/poquote")
public class LogicPoQuoteController extends BaseController<LogicPoQuoteDO>{

	private static final String MANAGER = "/yd/logic/poquote/PoquoteManager";
	private static final String EIDT = "/yd/logic/poquote/PoquoteOperation";// 添加、修改、显示页面
	
	@Resource(name="logicPoQuoteService")
	private ILogicPoQuoteService  logicPoQuoteService;
	
	@Resource(name = "syCodeService")
	private SyCodeService syCodeService;
	
	@Resource(name="basicCompanyService")
	private IBasicCompanyService basicCompanyService;
	
	@Resource(name="basicModeDeliveryService")
	private IBasicModeDeliveryService basicModeDeliveryService;
	
	@Resource(name="basicModePaymentService")
	private IBasicModePaymentService basicModePaymentService;
	
	@Resource(name = "scDepartmentService")
    private IScDepartmentService scDepartmentService;
	
	@Resource(name="poQuoteItemService")
	private ILogicPoQuoteItemService  poQuoteItemService;
	
	@Override
	public String manager(HttpServletRequest request, Model model)
			throws Exception {
		// TODO Auto-generated method stub
		return MANAGER;
	}

	@Override
	public void list(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		JqGridHandler hander=new JqGridHandler(request);
		SearchConditions scs = new SearchConditions();
//		scs.setRemovedProperty("removed");//判断是否有删除标识
		String gysID =request.getParameter("gysID");
		
		if(gysID!=null&&!"".equals(gysID)){
			scs.addCondition("gysid", gysID,SearchCondition.OP_EQUAL);
		}
		hander.getWheres(scs);	
		scs.setOrderBy("dctime desc");
		SearchResult result=	logicPoQuoteService.findListByExample(scs);
		OutJsonGrid out=new OutJsonGrid(result);
		out.printJSon(response);
	}

	@Override
	public String operationForm(HttpServletRequest request, @PathVariable String id,
			@PathVariable String flag, Model model) throws Exception {
		SearchConditions scs = new SearchConditions();
		List<BasicModeDeliveryDO> deliveryDOs=	basicModeDeliveryService.findListByExample(scs).getResults();
		
		SearchConditions scs1 = new SearchConditions();
		List<BasicModePaymentDO> modePaymentDOs=	basicModePaymentService.findListByExample(scs1).getResults();
		
		SearchConditions scs2 = new SearchConditions();
		List<ScDepartmentDO> sDepartmentDOs = scDepartmentService.findListByExample(scs2).getResults();
		if(OperationFlag.ADD.equals(flag)){//我新增加时操作
			BasicCompanyDO bcd=	basicCompanyService.findListById(id);
			model.addAttribute("bcd", bcd);
			model.addAttribute("flag", "add");
		}else{
			LogicPoQuoteDO poQuoteDOs=logicPoQuoteService.findListById(id);
			/*SearchConditions scs3 = new SearchConditions();
			scs3.addCondition("quote_id",poQuoteDOs.getId(),SearchCondition.OP_EQUAL);
			scs3.setOrderBy("materialscode asc");
			List<LogicPoQuoteItemDO> poQuoteItemDOs = poQuoteItemService.findListByExample(scs3).getResults();*/
			
			model.addAttribute("poQuoteDOs", poQuoteDOs);
			//model.addAttribute("poQuoteItemDOs", poQuoteItemDOs);
			model.addAttribute("flag", "edit");
		}
		model.addAttribute("deliveryDOs", deliveryDOs);
		model.addAttribute("modePaymentDOs", modePaymentDOs);
		model.addAttribute("sDepartmentDOs", sDepartmentDOs);
		return EIDT;
	}
	
	@RequestMapping("/griditems")
	public void griditems(HttpServletRequest request,HttpServletResponse response) throws Exception{
		String id = request.getParameter("id");
		if(StringUtils.isNotBlank(id)){
			LogicPoQuoteDO poQuoteDOs=logicPoQuoteService.findListById(id);
			SearchConditions scs3 = new SearchConditions();
			scs3.addCondition("quote_id",poQuoteDOs.getId(),SearchCondition.OP_EQUAL);
			scs3.setOrderBy("materialscode asc");
			List<LogicPoQuoteItemDO> poQuoteItemDOs = poQuoteItemService.findListByExample(scs3).getResults();
			OutJsonGrid out = new OutJsonGrid(poQuoteItemDOs);
			out.printJSon(response);
		}
	}

	@Override
	public Map<String, Object> save(HttpServletRequest request,
			LogicPoQuoteDO curAP, BindingResult result, Model model)
			throws Exception {
		BodyMsg bodyMap=BodyMsg.getInstance();
		String itemdata =request.getParameter("itemdata");
		if(itemdata==null&&"".equals(itemdata)){
			bodyMap.isFail();
			bodyMap.configWebInfor("物料单内容不能为空！");
			return bodyMap.modelMap;
		}
		try {
			logicPoQuoteService.poQuoteSave(request, curAP);
			bodyMap.isSuccess();
			bodyMap.configWebInfor(GlobalResLoader.getOpsuccess());
			bodyMap.configWebId(curAP.getId());
			
		} catch (Exception e) {			
			e.printStackTrace();
			bodyMap.isFail();
			bodyMap.configWebInfor(GlobalResLoader.getOpfailed()+e.getMessage());
		}
		return bodyMap.modelMap;
	}

	@Override
	public Map<String, Object> delete(HttpServletRequest request,
			HttpServletResponse response, Model model) throws Exception {
		BodyMsg bodyMap=BodyMsg.getInstance();
		try{
			String ids = request.getParameter("ids");
			String[] fields=ids.split(",");
			
			for(String field : fields){
				logicPoQuoteService.delete(field, SessionUtil.getUser(request));
			}
			bodyMap.isSuccess(GlobalResLoader.getOpsuccess());
		}catch(Exception e){
			e.printStackTrace();
			bodyMap.isFail(GlobalResLoader.getOpfailed()+e.getMessage());
		}
		return bodyMap.modelMap;
	}
	
	@RequestMapping(value = "/tree")
	public void treelist(HttpServletRequest request,HttpServletResponse response)throws Exception{
		String tr=null;
		JqGridHandler hander=new JqGridHandler(request);
		SearchConditions scs = new SearchConditions();
		scs.addCondition("parentname","供应商",SearchCondition.OP_EQUAL);
		hander.getWheres(scs);	
		scs.setOrderBy("name asc");
		List<BasicCompanyDO> list =basicCompanyService.findListByExample(scs).getResults();
		tr=tree(list);
		AjaxUtil.printJSonArr(response, tr);
	}
	
    /**
     * 自调函数 生成tree数据
     **/
	private String  tree(List<BasicCompanyDO> list) throws SyBaseException {
		StringBuffer sf =new StringBuffer();
		sf.append("[");
		for(int i=0;i<list.size();i++){
			sf.append("{");
			sf.append("\"text\":").append("\"").append(list.get(i).getName()).append("\"").append(",").append("\"id\":").append("\"").append(list.get(i).getId()).append("\"");
			if(i==(list.size()-1)){
				sf.append("}");
			}else{
				sf.append("},");
			}
		}
		sf.append("]");
		return sf.toString();
	}

//	@RequestMapping(value = "/updateState")
//	public void updateState(HttpServletRequest request,HttpServletResponse response)throws Exception{
//		String id = request.getParameter("rows");
//		Map<String,String> map =new HashMap<String, String>();
//		try{
//			LogicPoQuoteDO logicPoQuoteDO = logicPoQuoteService.findListById(id);
//			logicPoQuoteDO.setBillstatus(0);
//			logicPoQuoteService.update(logicPoQuoteDO,  SessionUtil.getUser(request));
//		map.put("msg", "SUCCESS");
//		}catch(Exception e){
//			e.printStackTrace();
//			map.put("msg", "ERROR");
//		}
//		AjaxUtil.printJSonArr(response, JSONObject.fromObject(map).toString());
//	}
	
	@RequestMapping(value = "/newPrice")
	public void polist(HttpServletRequest request,HttpServletResponse response,Model model)throws Exception{
			String materialsid = request.getParameter("materialsid");
			String gyscode = request.getParameter("gyscode");
			Map<String, Object> map = new HashMap<String, Object>();
			if(materialsid !=null && materialsid.length()>0){
				map.put("materialsid", materialsid);
			}
			if(gyscode !=null && gyscode.length()>0){
				map.put("gyscode", gyscode);
			}
			LogicPoQuoteItemDO lQuoteItemDO= logicPoQuoteService.findPrice(map);
			AjaxUtil.printJSonArr(response, JSONArray.toJSONString(lQuoteItemDO).toString());
	}
}
